﻿using ChoMy.Areas.Admin.Models;
using ChoMy.Constants;
using ChoMy.Helpers;
using ChoMy.Models;
using ChoMy.Models.Data;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;

namespace ChoMy.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        private ChoMyContext db = new ChoMyContext();
        private StringHelper strHp = new StringHelper();
        private FileHelper fileHp = new FileHelper();
        private CategoryHelper cateHp = new CategoryHelper();
        private string title = "sản phẩm";

        public ProductController()
        {
            ViewBag.Title = title;
        }

        [Authorize(Roles = "Admin, Product Read Public,  Product Read Private")]
        public ActionResult Index(int? categoryId, bool? isTrash, string search, string sortOrder, int? page, int? pageSize)
        {
            var sortList = new List<string> { "Name", "DateModified", "DateCreated", "Products.Count", "ListPrice", "Category.Name" };
            var pageSizeList = new List<int> { 10, 25, 50, 100 };
            int pageNumber = page ?? 1;

            pageSize = pageSize ?? 10;
            sortOrder = sortOrder ?? "DateCreated_desc";
            isTrash = isTrash ?? false;

            ViewBag.IsTrash = isTrash;
            ViewBag.PageSize = pageSize;
            ViewBag.PageSizeDDL = new SelectList(pageSizeList, pageSize);
            ViewBag.ReturnListUrl = Request.Url.AbsoluteUri;

            IQueryable<Product> query = db.Products;

            if (User.IsInRole("Product Read Private"))
            {
                query = query.Where(x => x.CreatedBy == User.Identity.Name);
            }

            ViewBag.TrashCount = query.Count(x => x.IsDelete);
            ViewBag.ListCount = query.Count(x => !x.IsDelete);

            query = CategoryFilter(query, categoryId);

            if (!String.IsNullOrWhiteSpace(search))
            {
                page = 1;

                query = Search(query, search.Trim());
            }

            query = Sort(query, sortOrder, sortList);

            query = query.Where(x => x.IsDelete == isTrash);

            return View(query.ToPagedList(pageNumber, (int)pageSize));
        }

        [Authorize(Roles = "Admin, Product Read Public,  Product Read Private")]
        public ActionResult _Details(int id)
        {
            Product product = db.Products.Find(id);

            if (User.IsInRole("Product Read Private") && product.CreatedBy != User.Identity.Name)
            {
                return null;
            }

            return PartialView(product);
        }

        [Authorize(Roles = "Admin, Product Create")]
        public ActionResult Create(string returnListUrl)
        {
            ViewBag.CategoryDDL = CategorySelectList(0);
            ViewBag.BrandDDL = BrandSelectList(0);
            ViewBag.ReturnListUrl = returnListUrl;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Product Create")]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(ProductCreator model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                var product = new Product();
                product.Name = model.Name.Trim();
                product.BrandId = model.BrandId;
                product.CategoryId = model.CategoryId;
                product.SourceLink = model.SourceLink;
                product.Summary = model.Summary;
                product.Description = model.Description;
                product.ListPrice = model.ListPrice;
                product.Code = model.Code == null
                    ? Path.GetRandomFileName().Replace(".", "").ToUpper()
                    : model.Code.Trim();
                product.NameId = strHp.Unsigned(product.Name + "-" + product.Code);

                db.Products.Add(product);
                db.SaveChanges();

                SaveHistory("Create", product.Name);
                AlertHandling("Create", product.Name);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.CategoryDDL = CategorySelectList(0);
            ViewBag.BrandDDL = BrandSelectList(0);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [Authorize(Roles = "Admin, Product Edit Public, Product Edit Private")]
        public ActionResult Edit(int? id, string returnListUrl)
        {
            if (id == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Product product = db.Products.Find(id);

            if (product == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            if (User.IsInRole("Product Edit Private") && product.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            var model = new ProductEditor();
            model.Id = product.Id;
            model.Name = product.Name;
            model.Code = product.Code;
            model.SourceLink = product.SourceLink;
            model.ListPrice = product.ListPrice;
            model.Summary = product.Summary;
            model.Description = product.Description;
            model.BrandId = product.BrandId;
            model.CategoryId = product.CategoryId;

            ViewBag.CategoryDDL = CategorySelectList(product.CategoryId);
            ViewBag.BrandDDL = BrandSelectList(product.BrandId);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Product Edit Public, Product Edit Private")]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(ProductEditor model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                Product product = db.Products.Find(model.Id);

                if (User.IsInRole("Product Edit Private") && product.CreatedBy != User.Identity.Name)
                {
                    return RedirectToAction("Unauthorized", "Error");
                }

                product.Name = model.Name.Trim();
                product.BrandId = model.BrandId;
                product.CategoryId = model.CategoryId;
                product.ListPrice = model.ListPrice;
                product.SourceLink = model.SourceLink;
                product.Summary = model.Summary;
                product.Description = model.Description;
                product.Code = model.Code == null
                    ? Path.GetRandomFileName().Replace(".", "").ToUpper()
                    : model.Code.Trim();
                product.NameId = strHp.Unsigned(product.Name + "-" + product.Code);
                product.DateModified = DateTime.Now;
                product.ModifiedBy = User.Identity.Name;

                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();

                SaveHistory("Edit", product.Name);
                AlertHandling("Edit", product.Name);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.CategoryDDL = CategorySelectList(model.CategoryId);
            ViewBag.BrandDDL = BrandSelectList(model.BrandId);
            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Product Delete Public, Product Delete Private")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, string returnListUrl)
        {
            Product product = db.Products.Find(id);

            if (User.IsInRole("Product Delete Private") && product.CreatedBy != User.Identity.Name)
            {
                return RedirectToAction("Unauthorized", "Error");
            }

            string productName = product.Name;            

            foreach (String url in product.Images.Select(x => x.Url))
            {
                fileHp.Delete(url);
            }

            db.Products.Remove(product);
            db.SaveChanges();

            SaveHistory("Delete", productName);
            AlertHandling("Delete", productName);

            if (!String.IsNullOrWhiteSpace(returnListUrl))
            {
                return Redirect(returnListUrl);
            }

            return RedirectToAction("Index", new { isTrash = true });
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Product Recycle Public, Product Recycle Private")]
        public ActionResult Recycle(int id)
        {
            Product product = db.Products.Find(id);

            if (User.IsInRole("Product Recycle Private") && product.CreatedBy != User.Identity.Name)
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }

            product.IsDelete = product.IsDelete ? false : true;
            product.DateModified = DateTime.Now;
            product.ModifiedBy = User.Identity.Name;

            db.Entry(product).State = EntityState.Modified;
            db.SaveChanges();

            if(product.IsDelete)
            {
                SaveHistory("Recycle-Delete", product.Name);
            }
            else
            {
                SaveHistory("Recycle-Restore", product.Name);
            }

            return Json(product.IsDelete ? 1 : 0, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CheckCode(string code, int? id)
        {
            code = code.Trim();

            Product product = db.Products.FirstOrDefault(x => x.Code == code && x.Id != id);

            if (product != null)
            {
                if (!product.IsDelete)
                {
                    string url = Url.Action("Index", new { search = code, isTrash = false });
                    string result = String.Format("Mã {0} này đã tồn tại. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string url = Url.Action("Index", new { search = code, isTrash = true });
                    string result = String.Format("Mã {0} này đã tạm thời bị xóa. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        #region Helpers
        private SelectList CategorySelectList(int categoryId)
        {
            IEnumerable<Category> categories = cateHp.Leaf()
                .Where(x => !x.IsDelete)
                .OrderBy(x => x.Name);

            return new SelectList(categories, "Id", "Name", categoryId);
        }

        private SelectList BrandSelectList(int brandId)
        {
            IQueryable<Brand> brands = db.Brands
                .Where(x => !x.IsDelete)
                .OrderBy(x => x.Name);

            return new SelectList(brands, "Id", "Name", brandId);
        }

        private void SaveHistory(string crud, string name)
        {
            string type = "Product";

            DateTime dateTime = DateTime.Now;
            string userName = User.Identity.Name;
            string description = "";

            switch(crud)
            {
                case "Create":
                    description = String.Format("<b>{0}</b> tạo mới {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Edit":
                    description = String.Format("<b>{0}</b> chỉnh sửa {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Delete":
                    description = String.Format("<b>{0}</b> xóa vĩnh viễn {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Recycle-Delete":
                    description = String.Format("<b>{0}</b> xóa tạm thời {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Recycle-Restore":
                    description = String.Format("<b>{0}</b> khôi phục {1} <b>{2}</b>", userName, title, name);
                    break;
            }

            var history = new History();
            history.DateTime = dateTime;
            history.Description = description;
            history.HistoryTypeId = db.HistoryTypes.First(x => x.Name == type).Id;

            db.Histories.Add(history);
            db.SaveChanges();
        }

        private void AlertHandling(string crud, string name)
        {
            string userName = User.Identity.Name;
            string alertMessage = "";

            switch (crud)
            {
                case "Create":
                    alertMessage = String.Format("Bạn vừa tạo mới {0}: <b>{1}</b>", title, name);
                    break;
                case "Edit":
                    alertMessage = String.Format("Bạn vừa chỉnh sửa {0}: <b>{1}</b>", title, name);
                    break;
                case "Delete":
                    alertMessage = String.Format("Bạn vừa xóa vĩnh viễn {0}: <b>{1}</b>", title, name);
                    break;
            }

            if (!String.IsNullOrWhiteSpace(alertMessage))
            {
                Session["alert-message-" + userName] = alertMessage;
                Session["alert-type-" + userName] = "alert-success";
            }            
        }

        private IQueryable<Product> CategoryFilter(IQueryable<Product> query, int? categoryId)
        {
            List<Category> categories = query
               .Where(x => !x.IsDelete)
               .GroupBy(x => x.Category)
               .Select(x => x.Key)
               .OrderBy(x => x.Name)
               .ToList();

            ViewBag.CategoryDDL = new SelectList(categories, "Id", "Name", categoryId);

            if (categoryId != null)
            {
                ViewBag.CategoryId = categoryId;

                query = query.Where(x => x.CategoryId == categoryId);
            }

            return query;
        }

        private IQueryable<Product> Search(IQueryable<Product> query, string search)
        {
            ViewBag.Search = search;

            search = strHp.Unsigned(search);

            query = query.Where(x => x.NameId.Contains(search) || x.Category.NameId.Contains(search));

            return query;
        }

        private IQueryable<Product> Sort(IQueryable<Product> query, string sortOrder, List<string> sortList)
        {
            ViewBag.SortOrder = sortOrder;

            foreach (string sort in sortList)
            {
                ViewData[sort + "Sort"] = sortOrder == sort + "_desc" ? sort : sort + "_desc";
            }

            if (sortOrder.Contains("_desc"))
            {
                sortOrder = sortOrder.Replace("_desc", "");
                query = query.OrderBy(sortOrder + " descending");
                ViewData[sortOrder + "Icon"] = DataTableConstant.DescSortIcon;
            }
            else
            {
                query = query.OrderBy(sortOrder);
                ViewData[sortOrder + "Icon"] = DataTableConstant.AscSortIcon;
            }

            return query;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }
        #endregion
    }
}